package com.hube.platform.tenant.configuration;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hube.platform.tenant.entity.dto.UserContext;
import com.hube.platform.tenant.helper.UserContextHolder;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * <p>
 * 自定义数据插入更新前处理Handler
 * </p>
 */
@Component
public class MybatisMetaObjectHandler implements MetaObjectHandler {

    private final static String CREATE_DATE = "createDate";
    private final static String CREATE_BY = "createBy";
    private final static String UPDATE_DATE = "updateDate";
    private final static String UPDATE_BY = "updateBy";
    private final static String DELETE_FLAG = "deleteFlag";

    @Override
    public void insertFill(MetaObject metaObject) {
        Date now = new Date();
        UserContext userContext = UserContextHolder.getCurrentUser();
        if (Objects.isNull(userContext)) {
            userContext = new UserContext();
        }

        Object createDate = getFieldValByName(CREATE_DATE, metaObject);
        if (createDate == null) {
            this.strictInsertFill(metaObject, CREATE_DATE, Date.class, now);
        }

        Object createBy = getFieldValByName(CREATE_BY, metaObject);
        if (createBy == null) {
            this.strictInsertFill(metaObject, CREATE_BY, String.class, userContext.getUserId());
        }

        Object delFlag = getFieldValByName(DELETE_FLAG, metaObject);
        if (delFlag == null) {
            this.strictInsertFill(metaObject, DELETE_FLAG, Integer.class, 0);
        }
        updateCustomModifiedFields(metaObject, userContext);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        UserContext userContext = UserContextHolder.getCurrentUser();
        if (Objects.isNull(userContext)) {
            userContext = new UserContext();
        }
        updateCustomModifiedFields(metaObject, userContext);
    }

    private void updateCustomModifiedFields(MetaObject metaObject, UserContext userContext) {
        Date now = new Date();
        Object updateDate = getFieldValByName(UPDATE_DATE, metaObject);
        if (updateDate == null) {
            this.strictUpdateFill(metaObject, UPDATE_DATE, Date.class, now);
        }

        Object updateBy = getFieldValByName(UPDATE_BY, metaObject);
        if (updateBy == null) {
            this.strictUpdateFill(metaObject, UPDATE_BY, String.class, userContext.getUserId());
        }
    }
}
